package com.sky.chapter3.lock;


import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : wushikai
 * <p>
 * date : 2022-07-04
 * ReentrantLock 的 公平锁
 */
public class LockDemo4 {
    private static int num = 0;
    private static ReentrantLock fairLock = new ReentrantLock(true);   //构造公平锁

    public static class T extends Thread {
        T(String name) {
            super(name);
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                fairLock.lock();
                try {
                    System.out.println(this.getName() + "获得锁!");
                } finally {
                    fairLock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //先来先得, 后来后得 ;
        // 生活中，排队讲求先来后到视为公平。程序中的公平性也是符合请求锁的绝对时间的，其实就是 FIFO，否则视为不公平
        T t1 = new T("t1");
        T t2 = new T("t2");
        T t3 = new T("t3");

        t1.start();
        t2.start();
        t3.start();


        t1.join();
        t2.join();
        t3.join();
    }
}

